/**
 * @author lihongyang
 * @since 16/9/22
 */
;(function ($, window, document) {
    var id;
    var timer;
    var mobile;
    var docMain = {
        captcha: $('#captcha'),
        captchaCon: $('#captchaCon'),
        captchaParent: $('#captchaParent')
    };
    if (thymeleafData.needCaptcha) {
        docMain.captchaParent.show();
    }
    $('input[type=text]').placeholder();
    docMain.captchaCon.click(function () {
        reloadCaptcha(this);
    });
    //step1
    $("#choose").click(function () {
        var userId = $("#userId").val();
        if (userId !== "") {
            $.ajax({
                url: '/password/findWay',
                type: 'post',
                data: {name: userId},
                async: false,
                success: function (data) {
                    if (data.id) {
                        id = data.id;
                        var mbl = $("#userId").val();
                        //用户名非手机号
                        if(isNaN(mbl)){
                            if(mbl.length>2){
                                mobile = mbl.substring(0, 1) + "****" + mbl.substring(mbl.length-1, mbl.length);
                            }else{
                                mobile = mbl.substring(0, 1) + "****";
                            }
                        }else{
                            mobile = mbl.substring(0, 3) + "****" + mbl.substring(7, 11);
                        }
                        $(".show").removeClass("show");
                        $(".status2").addClass("show");
                        if (data.exitEmail) {
                            $("#email-box").show();
                        }
                        if (data.exitMobile) {
                            $("#mobile-box").show();
                        }
                        $("#userName").text(mobile);
                        $("#userName1").text(mobile);
                    } else {
                        $("#userError").text(data.error);
                        $(".input-con").eq(0).css({"borderColor": "#e52e04"});
                    }
                }
            });
        } else {
            $('#userError').text('输入帐号不能为空');
            $(".input-con").eq(0).css({"borderColor": "#e52e04"});
        }
    });
    //step2_1通过手机验证的方式
    $("#goToMobile").click(function () {
        var userId = $("#userId").val();
        if (userId !== "") {
            $.ajax({
                url: '/password/mobile/choose',
                type: 'post',
                data: {name: userId, id: id},
                async: false,
                success: function (data) {
                    var mobile = data.mobile.substring(0, 3) + "****" + data.mobile.substring(7, 11);
                    $(".show").removeClass("show");
                    $(".status3").addClass("show");
                    $(".status3_2").addClass("show");
                    $("#userMobile").attr("data-mobile", data.mobile).text(mobile);
                }
            });
        } else {
            $('#userError').text('帐号不能为空');
        }
    });
    //返回验证方式选择
    $("#mobileReturn").click(function () {
        $(".show").removeClass("show");
        $(".status2").addClass("show");
    });
    //step2_2通过邮箱验证的方式
    $("#goToEmail").click(function () {
        var userId = $("#userId").val();
        if (userId !== "") {
            $.ajax({
                url: '/password/email/choose',
                type: 'post',
                data: {name: userId, id: id},
                async: false,
                success: function (data) {
                    $(".show").removeClass("show");
                    $(".status3").addClass("show");
                    $(".status3_1").addClass("show");
                    $("#email_address").text(data.email);
                    $("#goEmail").attr("href", data.url);
                }
            });
        } else {
            $('#userError').text('帐号不能为空');
        }
    });
    //step2_2重新发送邮箱验证
    $("#getEmail").click(function () {
        var userId = $("#userId").val();
        if (userId !== "") {
            $.ajax({
                url: '/password/email/choose',
                type: 'post',
                data: {name: userId, id: id},
                async: false,
                success: function (data) {
                    $(".show").removeClass("show");
                    $(".status3").addClass("show");
                    $(".status3_1").addClass("show");
                    $("#email_address").text(data.email);
                    $("#goEmail").attr("href", data.url);
                }
            });
        } else {
            $('#userError').text('帐号不能为空');
        }
    });
    //返回验证方式选择
    $("#emailReturn").click(function () {
        $(".show").removeClass("show");
        $(".status2").addClass("show");
    });
    $("#other_type").click(function () {
        $(".show").removeClass("show");
        $(".status2").addClass("show");
    });
    //step2_0手机验证页面
    $("#setPwdByMobile").click(function () {
        var userId = $("#userId").val();
        var activation = $("#mobileCode").val();
        if (activation === '') {
            $('#codeError').text('请输入短信验证码').css({"color": "#e52e04"});
            $(".input-con").eq(3).css({"borderColor": "#e52e04"});
            return false;
        }
        if (thymeleafData.needCaptcha && docMain.captcha.val() === '') {
            $('#codeError').text('请输入字符验证码');
            return false;
        }
        if (userId) {
            $.ajax({
                url: '/password/validate',
                type: 'post',
                data: {
                    mobile: $("#userMobile").attr("data-mobile"),
                    activation: activation,
                    captcha: docMain.captcha.val()
                },
                success: function (data) {
                    if (checkMobileCode(activation) === true && activation !== "") {
                        $(".show").removeClass("show");
                        $(".status3").addClass("show");
                        $(".status3_0").addClass("show");
                    } else if (data.error) {
                        $('#codeError').text(data.error);
                        reloadCaptcha(docMain.captchaCon);
                    }
                }
            });
        } else {
            $('#userError').text('帐号不能为空');
        }
    });
    //step3成功页面
    $("#updatePwd").click(function () {
        var userId = $("#userId").val();
        var password = $('#pwd').val();
        var result = checkPwd(password);
        if (result === true) {
            $('#pwdError').text('');
            var confirm = eqPwd();
            if (confirm === true) {
                $.ajax({
                    url: '/password/modify_by_mobile',
                    type: 'post',
                    data: {
                        id: id,
                        mobile: $("#userMobile").attr("data-mobile"),
                        newPassword: $("#pwdRepeat").val(),
                        activationCode: $("#mobileCode").val(),
                        captcha: docMain.captcha.val()
                    },
                    async: false,
                    success: function () {
                        $(".show").removeClass("show");
                        $(".status4").addClass("show");
                    }
                });
            }
        } else {
            $('#pwdError').text(" " + result);
        }
    });

    /********验证相关*********/

    // //获取地址栏值
    // function getQueryString(name){
    //     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    //     var r = window.location.search.substr(1).match(reg);
    //     if(r!==null){return  unescape(r[2]);}
    //     return null;
    // }

    //      邮箱检测是否符合标准
    function checkEmail(str) {
        var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,
            emailBox = $("#email-box");
        if (re.test(str)) {
            emailBox.find(".icon-success").show();
            emailBox.find(".icon-error").hide();
            $("#emailerr").hide();
            $("#email").removeClass("error");
        } else {
            emailBox.find(".icon-error").show();
            emailBox.find(".icon-success").hide();
            $("#emailerr").show();
            $("#email").addClass("error");
        }
    }

    //      密码强度检测
    function pwdStrong(str) {
        var lv = 0;
        if (str.match(/[a-z]/g)) {
            lv++;
        }
        if (str.match(/[0-9]/g)) {
            lv++;
        }
        if (str.match(/(.[^a-z0-9])/g)) {
            lv++;
        }
        if (lv > 3) {
            lv = 3;
        }
        return lv;
    }

    //获取短信验证码
    $("#getMobileCode").click(function () {
        var captcha = docMain.captcha.val();
        if (thymeleafData.needCaptcha && captcha === '') {
            $('#codeError').text('请输入字符验证码');
            return false;
        }
        $.ajax({
            url: '/mobile/send',
            data: {mobile: $("#userMobile").attr('data-mobile'), type: 201, captcha: captcha.toLowerCase()},
            type: 'get',
            async: false,
            success: function (data) {
                $('#codeError').text('');
                switch (data.result) {
                    case true:
                        countdown(60);
                        break;
                    case 'needCaptcha':
                        reloadCaptcha(docMain.captchaCon);
                        docMain.captchaParent.show();
                        thymeleafData.needCaptcha = true;
                        break;
                    default:
                        reloadCaptcha(docMain.captchaCon);
                        break;
                }
                if (data.error) {
                    $('#codeError').text(data.error);
                }
            }
        });
    });
    //按钮计时器
    function countdown(time) {
        timer = setTimeout(function () {
            countdown(time);
        }, 1000);
        var val = document.getElementById('getMobileCode');
        if (time === 0) {
            val.removeAttribute("disabled");
            val.innerText = "重新发送";
            clearTimeout(timer);
        } else {
            val.setAttribute("disabled", "disabled");
            val.innerText = "重新发送(" + time + ")";
            time--;
        }
    }

    //检测用户手机和验证码是否匹配
    function checkMobileCode(code) {
        var flag = false;
        if (code === "") {
            return '请输入验证码';
        } else {
            var getData = {
                code: code,
                mobile: $("#userMobile").attr("data-mobile"),
                type: 201,
                captcha: docMain.captcha.val()
            };
            $.ajax({
                url: "/mobile/check",
                async: false,
                type: 'get',
                data: getData,
                success: function (data) {
                    if (data.result === true) {
                        flag = true;
                    } else if (data.result === false) {
                        flag = false;
                    }
                }
            });
        }
        return flag;
    }
    //进行密码校验
    function checkPwd(str) {
        var re = /^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{6,20}$/;
        if (str.length === 0) {
            return '密码不能为空';
        }
        else if (str.length < 6) {
            return '密码太短，至少6个字符';
        }
        else if (str.length > 20) {
            return '密码过长,不能超过20个字符';
        }
        else if (re.test(str)) {
            return true;
        }
        else {
            return '密码格式不正确';
        }
    }

    //密码二次校验
    function eqPwd() {
        var oldPwd = $('#pwd').val();
        var newPwd = $("#pwdRepeat").val();
        var _this = $('#pwdError2');
        if (oldPwd === newPwd) {
            _this.text('');
            return true;
        }
        else if (newPwd.length === 0) {
            _this.text('密码不能为空');
            return false;
        }
        else if (newPwd.length > 20) {
            _this.text('密码过长,不能超过20个字符');
            return false;
        }
        else if (newPwd.length < 6) {
            _this.text('密码太短，至少6个字符');
            return false;
        }
        else {
            _this.text('两次密码输入不一致');
            return false;
        }
    }

    //刷新图形验证码
    function reloadCaptcha(e) {
        var date = new Date().getTime();
        $(e).html('<img width="130px" height="46px" src="/captcha?' + date + '"/>');
        $(e).prev().val(null);
        $(e).prev().focus();
    }

})(jQuery, window, document);